package com.training.bt.tracker;

import com.training.bt.entity.Resource;
import com.training.bt.resource.service.ResourceService;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.List;

@Slf4j
@Component
@RequiredArgsConstructor
public class TorrentInitializer implements CommandLineRunner {

    private final ResourceService resourceService;
    private final CustomTracker customTracker;

    @Override
    public void run(String... args) throws Exception {

        try {
            log.info("Initializing tracker mappers...");
            Class.forName("com.training.bt.tracker.CustomTrackedTorrent");
            log.info("Tracker mappers initialized");
        } catch (ClassNotFoundException e) {
            log.error("Failed to initialize tracker mappers", e);
        }
        log.info("开始重新注册所有活跃的种子文件...");

        Thread.sleep(3000);
        // 获取所有已审核通过的资源
        List<Resource> activeResources = resourceService.getAllActiveResources();
        log.info("找到 {} 个需要重新注册的种子", activeResources.size());

        int successCount = 0;
        int errorCount = 0;

        for (Resource resource : activeResources) {
            try {
                File torrentFile = new File(resource.getFilePath());
                if (torrentFile.exists()) {
                    // 重新注册到Tracker
                    customTracker.announce(CustomTrackedTorrent.load(torrentFile));
                    successCount++;
                    log.debug("种子重新注册成功: {} - {}", resource.getId(), resource.getTitle());
                } else {
                    log.warn("种子文件不存在: {} - {}", resource.getId(), resource.getFilePath());
                    errorCount++;
                }
            } catch (Exception e) {
                log.error("种子重新注册失败: {} - {}: {}", resource.getId(), resource.getTitle(), e.getMessage());
                errorCount++;
            }
        }

        log.info("种子重新注册完成: 成功 {} 个, 失败 {} 个", successCount, errorCount);

    }
}